package com.uni.service.impl;

import com.uni.dao.RoleMapper;
import com.uni.dao.UserMapper;
import com.uni.dao.UserRoleMapper;
import com.uni.pojo.*;
import com.uni.service.UserService;
import com.uni.utils.SaltUtils;
import com.uni.utils.UserInfoUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/1/28 10:53
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;

    @Override
    public User login(User user) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getCode(), user.getPwd(), false);
        Subject currentUser = SecurityUtils.getSubject();
        try{
            currentUser.login(token);
            // 登录成功后获取用户所有信息，并设置[生日]字段的格式化
            User userInfo = getUserByCode(user.getCode());
            userInfo.setBirthdayString(UserInfoUtil.decodeBirthday(userInfo.getBirthday()));
            return userInfo;
        } catch(Exception e){
            token.clear();
            return null;
        }
    }

    @Override
    public User getUserByCode(String userCode) {
        User user = null;
        List<User> users = userMapper.selectByExampleWithBLOBs(new UserExample() {{
            createCriteria().andCodeEqualTo(userCode);
        }});
        // 检查用户是否存在
        if(users != null && users.size() == 1) {
            user = users.get(0);
            // 设置角色
            user.setRole(roleMapper.selectByUserCode(user));
            // 设置地区
            user.setAddressDetail(UserInfoUtil.decodeAddress(user.getAddress()));
            // 格式化生日
            user.setBirthdayString(UserInfoUtil.decodeBirthday(user.getBirthday()));
        }
        return user;
    }

    @Override
    public User update(User user) {
        List<User> users = userMapper.selectByExampleWithBLOBs(new UserExample() {{
            createCriteria().andCodeEqualTo(user.getCode());
        }});
        if (users != null && users.size() == 1) {
            User dbUser = users.get(0);
            // 同步部分字段
            dbUser.setUsername(user.getUsername());
            dbUser.setGender(user.getGender());
            dbUser.setBirthdayString(user.getBirthdayString());
            dbUser.setAddressDetail(user.getAddressDetail());
            // 转化[地址]的格式
            dbUser.setAddress(UserInfoUtil.encodeAddress(user.getAddressDetail()));
            // 转化[生日]的格式
            dbUser.setBirthday(UserInfoUtil.encodeBirthday(user.getBirthdayString()));
            // 联系电话
            dbUser.setPhone(user.getPhone());
            System.out.println(dbUser);
            return userMapper.updateByPrimaryKeySelective(dbUser) == 1 ? dbUser : null;
        } else return null;
    }
    @Override
    public User updateImg(User user) {
        return userMapper.updateByPrimaryKeySelective(user) == 1 ? user : null;
    }

    @Override
    public User register(User user) {
        /* 字段处理 */
        // 设置密文密码
        //     生成随机盐
        String salt = SaltUtils.getSalt(8);
        //     将随机盐保存到数据库
        user.setSalt(salt);
        //     对明文密码进行 md5 + salt + hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPwd(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        // 生日字段，存储编码
        user.setBirthday(UserInfoUtil.encodeBirthday(user.getBirthdayString()));
        // 地区字段，拼接省市区+详细地址
        user.setAddress(UserInfoUtil.encodeAddress(user.getAddressDetail()));
        // 根据性别设置默认头像
        user.setImg(user.getGender() == 1 ?
                "/images/user_woman.png" : "/images/user_man.png");
        //保存用户
        return userMapper.insert(user) == 1 ? getUserByCode(user.getCode()) : null;
    }

    @Override
    public List<User> getAllUser() {
        List<User> users = userMapper.selectByExampleWithBLOBs(new UserExample());
        // 查询用户角色 + 设置用户所在地 + 格式化生日
        users.forEach(user -> {
            // 设置角色
            user.setRole(roleMapper.selectByUserCode(user));
            // 设置所在地
            user.setAddressDetail(UserInfoUtil.decodeAddress(user.getAddress()));
        });
        return users;
    }

    @Override
    public List<User> getUserByMapPojos(Map<String, String> paramMap) {
        return userMapper.selectBySome(paramMap);
    }

    @Override
    public List<User> getUserRoleByMapPojos(Map<String, String> paramMap) {
        return userMapper.selectCodeWithRole(paramMap);
    }

    @Override
    public User addUserWithRole(User user, Integer rid, Address address) {
        // 用户特殊字段处理
        user.setAddress(UserInfoUtil.encodeAddress(address));       // 编码地址
        user.setBirthday(UserInfoUtil.encodeBirthday(user.getBirthdayString()));    // 编码生日
        // 生成随机盐
        String salt = SaltUtils.getSalt(8);
        user.setSalt(salt);
        // 根据性别设置默认头像
        user.setImg(user.getGender() == 1 ?
                "/images/user_woman.png" : "/images/user_man.png");
        //  对明文密码进行 md5 + salt + hash散列
        user.setPassword(new Md5Hash(user.getPwd(), salt, 1024).toHex());
        // 插入用户
        int i = userMapper.insertSelective(user);
        // 插入后查询对应的ID
        User resultUser = null;
        if(i == 1) {
            resultUser = userMapper.selectByCode(user);
            // 插入用户-角色表
            i += userRoleMapper.insertSelective(new UserRole(resultUser.getId(), rid));
        }
        return i == 2 ? user : null;
    }

    @Override
    public int removeUserById(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int removeUserByIds(List<Long> ids) {
        int i = userMapper.deleteByPrimaryKeys(ids);
        i += userRoleMapper.deleteByUserIds(ids);
        return i;
    }
}
